/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.biz.service.impl;

import me.zhengjie.modules.biz.domain.Settings;
import me.zhengjie.modules.biz.service.mapstruct.SettingsMapper;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.biz.repository.SettingsRepository;
import me.zhengjie.modules.biz.service.SettingsService;
import me.zhengjie.modules.biz.service.dto.StorehousrConfigDto;
import me.zhengjie.modules.biz.service.dto.StorehousrConfigQueryCriteria;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author Admin
* @date 2023-05-04
**/
@Service
@RequiredArgsConstructor
public class SettingsServiceImpl implements SettingsService {

    private final SettingsRepository settingsRepository;
    private final SettingsMapper settingsMapper;

    @Override
    public Map<String,Object> queryAll(StorehousrConfigQueryCriteria criteria, Pageable pageable){
        Page<Settings> page = settingsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(settingsMapper::toDto));
    }

    @Override
    public List<StorehousrConfigDto> queryAll(StorehousrConfigQueryCriteria criteria){
        return settingsMapper.toDto(settingsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public StorehousrConfigDto findById(Integer id) {
        Settings settings = settingsRepository.findById(id).orElseGet(Settings::new);
        ValidationUtil.isNull(settings.getId(),"StorehousrConfig","id",id);
        return settingsMapper.toDto(settings);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public StorehousrConfigDto create(Settings resources) {
        return settingsMapper.toDto(settingsRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Settings resources) {
        Settings settings = settingsRepository.findByKey(resources.getKey()).orElseGet(Settings::new);
        ValidationUtil.isNull( settings.getKey(),"StorehousrConfig","key",resources.getKey());
        settings.copy(resources);
        settingsRepository.save(settings);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            settingsRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<StorehousrConfigDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (StorehousrConfigDto storehousrConfig : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("配置名称", storehousrConfig.getKey());
            map.put("配置值", storehousrConfig.getValue());
            map.put("创建时间", storehousrConfig.getCreatedAt());
            map.put("修改时间", storehousrConfig.getUpdatedAt());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    public void updateAll(Map<String, Object> resources) {
        Set<String> keySet = resources.keySet();
        // 遍历keySet，并输出key的值
        for(String key : keySet){
            Settings temp = settingsRepository.findByKey(key).orElseGet(Settings::new);
            ValidationUtil.isNull( temp.getKey(),"StorehousrConfig","key", key);
            temp.setValue(resources.get(key).toString());
            settingsRepository.save(temp);
        }
    }

    @Override
    public Map<String, Object> queryByKeys(StorehousrConfigQueryCriteria criteria){
        List<Settings> settingsList = settingsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder));
        Map<String, Object> dataMap = new HashMap<>();

        for (Settings settings : settingsList) {
            dataMap.put(settings.getKey(), settings.getValue());
        }
        return dataMap;
    }
}
